package com.ocom.company.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.master.EntityMngAccountInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.company.MngAccountInfoRequest;
import com.ocom.common.utils.StringUtils;
import com.ocom.company.dao.IDaoMngAccountInfo;
import com.ocom.company.service.MngAccountInfoService;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MngAccountInfoServiceImpl extends ServiceImpl<IDaoMngAccountInfo, EntityMngAccountInfo> implements MngAccountInfoService {

    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    @Override
    public List<EntityMngAccountInfo> selectAccountsByPhone(MngAccountInfoRequest request) {
        QueryWrapper<EntityMngAccountInfo> wrapper = Wrappers.query();
        wrapper.eq(StringUtils.isNotEmpty(request.getUserId()),"user_id", request.getUserId())
               .eq(StringUtils.isNotEmpty(request.getPhone()),"phone", request.getPhone())
               .eq(StringUtils.isNotEmpty(request.getThirdType()),"third_type", request.getThirdType());
        return this.list(wrapper);
    }
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    @Override
    public Object addMngAccount(MngAccountInfoRequest request) throws Exception {
        QueryWrapper<EntityMngAccountInfo> wrapper = Wrappers.query();
        wrapper.eq("user_id",request.getUserId())
               .eq("third_type","1");

        EntityMngAccountInfo entityMngAccountInfo = baseMapper.selectOne(wrapper);
        if (!ObjectUtil.isEmpty(entityMngAccountInfo)){
            throw new Exception("当前账号已绑定手机号");
        }
        QueryWrapper<EntityMngAccountInfo> wrapper2 = Wrappers.query();
        wrapper2.eq("phone",request.getPhone());
        EntityMngAccountInfo entityMngAccountInfo2 = baseMapper.selectOne(wrapper2);
        if (!ObjectUtil.isEmpty(entityMngAccountInfo2)){
            throw new Exception("当前手机号已被其它账号绑定");
        }
        EntityMngAccountInfo entityMngAccountInfo3 =new EntityMngAccountInfo();
        BeanUtil.copyProperties(request,entityMngAccountInfo3);
        this.save(entityMngAccountInfo3);
        return null;
    }
}
